import { allCenter, safeRemoveFromFather } from "./uiUtils";
import { formatMsg } from "../../misc/lan";
import { promiseCallback } from "../../misc/promise";
import { MainWindow, LayerEnum } from "../../window/MainWindow";

function getBoxLayer(): egret.DisplayObjectContainer {
	return MainWindow.ins().getLayer(LayerEnum.msgbox)
}

interface MsgBoxParam {
	msg: string;
	format?: string;

	ok?: string;
	cancel?: string;
	check?: string;
}

// ok 1 ,cancel 0
type msgboxCallback = (rt: number) => void;

export function msgbox(text: string, func: msgboxCallback): void {
	// msgline(Text);
	const box = new DlgMsgbox(text, func);
	getBoxLayer().addChild(box);
}

export function msgboxParam(param: MsgBoxParam, func: msgboxCallback): void {
	const msg = formatMsg(param.msg, param.format);
	msgbox(msg, func);
}

export async function msgboxParamPromise(param: MsgBoxParam): Promise<number> {
	return promiseCallback(msgboxParam)(param);
}

class DlgMsgbox extends eui.Component {
	constructor(msg: string, func: msgboxCallback) {
		super();
		this.skinName = 'ui_msgboxSkin';
		this.msg = msg;
		this.callback = func;
		allCenter(this);
	}

	ok: eui.Button;

	cancel: eui.Button;

	ti: eui.Label;

	msg: string;

	callback: msgboxCallback;

	childrenCreated(): void {
		super.childrenCreated();
		this.createTi();
		this.ok.addEventListener('touchTap', this.onOk, this);
		this.cancel.addEventListener('touchTap', this.onCancel, this);
	}

	protected createTi(): void {
		this.ti.text = this.msg;
	}

	onOk(): void {
		safeRemoveFromFather(this);
		this.callback(1);
	}

	onCancel(): void {
		safeRemoveFromFather(this);
		this.callback(0);
	}

	onEsc(): void {
		this.callback(0);
	}

	async onClose(): Promise<void> {
		this.onCancel();
	}
}
